<template>
  <layout>
    <!-- 顶部操作 -->
    <section slot="search">
      <custom-form
        ref="search-form"
        class="search-form"
        v-model="tableSearch"
        layout="inline"
        :FormList="searchColumns"
      >
        <span style="margin: 20px 0;">
          <b>行政区划信息管理</b>
        </span>
        <a-button class="action-button" type="primary" @click="search()"
          >刷新</a-button
        >
        <!-- <a-button
          class="action-button"
          type="primary"
          @click="tableAdd"
        >添加顶级行政区</a-button> -->
      </custom-form>
      <!-- <a-input placeholder="产品名称或者编号" v-model="tableSearch.searchKey" allowClear style="width: 200px;" /> -->
    </section>

    <vxe-table
      border
      resizable
      ref="xTree"
      row-id="s_a_id"
      :tree-config="{
        lazy: true,
        children: 'children',
        hasChild: 'hasChild',
        loadMethod: loadChildrenMethod,
      }"
      :menu-config="{ body: { options: bodyMenus }, visibleMethod }"
      :data="tableData"
      @menu-click="contextMenuClickEvent"
    >
      <vxe-table-column
        v-for="(item, index) in tableColumns"
        :key="item.key"
        :field="item.key"
        :width="item.width"
        :title="item.title"
        :tree-node="index === 0"
      ></vxe-table-column>

      <vxe-table-column title="操作" width="300">
        <template v-slot="{ row }">
          <a-button
            class="action-button"
            type="link"
            auth="area.edit"
            @click="handleTableEdit(row)"
            >编辑</a-button
          >
          <a-button
            class="action-button"
            type="link"
            auth="area.next"
            @click="handleAddNext(row)"
            >添加下级行政区划</a-button
          >
          <a-popconfirm
            title="您确认要删除该条数据?"
            ok-text="确认"
            cancel-text="取消"
            @confirm="tableDel(row)"
          >
            <a-button
              v-if="row.s_a_id && row.s_a_id.length > 6"
              class="action-button"
              type="link"
              auth="area.delete"
              >删除</a-button
            >
          </a-popconfirm>
        </template>
      </vxe-table-column>
    </vxe-table>

    <!-- 编辑产品数据 -->
    <a-modal
      :visible="visible"
      :title="visibleTitle"
      :footer="null"
      @cancel="visible = false"
    >
      <custom-form
        ref="custom-form"
        class="custom-form"
        v-model="currentRow"
        :FormList="formColumns"
        :mode="formMode"
        layout="horizontal"
      ></custom-form>
      <!-- <section slot="footer"> -->
      <a-button @click="handlerFromSubmit" type="primary">提交</a-button>
      <!-- </section> -->
    </a-modal>
  </layout>
</template>

<script lang="ts">
import { Mixins, Component, Watch, Vue } from 'vue-property-decorator'
import { State, Mutation, Getter, namespace } from 'vuex-class'
import EventsMixin from '@/mixin/events'
import { TableMixin, AuthMixin } from '@/mixin'

import { TableLayout } from '@/layouts'
import CustomForm from '@/components/src/Form'
import { areaServices, IArea } from '@/common/services/area'
import { userModule } from '@/store/modules/user'

@Component({
  components: {
    Layout: TableLayout,
    CustomForm,
  },
})
export default class AdminList extends Mixins(
  EventsMixin,
  TableMixin,
  AuthMixin
) {
  get currentUserArea() {
    return userModule.currentUserArea
  }

  // 产品列表搜索条件
  public tableSearch = {
    page: 1,
    pageSize: 15,
    s_a_id: this.currentUserArea.s_a_id,
  }

  public isShowIndexColumn = false

  public bodyMenus = [
    [
      { code: 'clearLoaded', name: '清除加载状态', disabled: false },
      { code: 'reloadNodes', name: '重新加载子节点', disabled: false },
      { code: 'expand', name: '展开节点', disabled: false },
      { code: 'contract', name: '收起节点', disabled: false },
    ],
  ]

  // 产品列表表格信息
  public columns: ITable.IColumn[] = [
    {
      title: '上级行政地区编号',
      dataIndex: 's_up_id',
      key: 's_up_id',
      width: '50%',
      form: {
        type: 'a-input',
        placeholder: '',
        disabled: true,
        isShowList: false,
      },
    },
    {
      title: '行政区划',
      dataIndex: 's_a_nam',
      key: 's_a_nam',
      align: 'right',
      width: 300,
      form: {
        type: 'a-input',
        placeholder: '请输入行政地区名称',
        isShowQuery: false,
      },
    },
    {
      title: '行政编号',
      dataIndex: 's_a_id',
      key: 's_a_id',
      align: 'right',
      width: 200,
      form: {
        type: 'a-input',
        placeholder: '自动生成',
        disabled: true,
      },
    },
    // {
    //   title: '操作',
    //   key: 'action',
    //   width: 340,
    //   scopedSlots: { customRender: 'action' }
    // }
  ]

  public tableApi = {
    list: areaServices.getAreaLazy,
    add: areaServices.editArea,
    edit: areaServices.editArea,
    del: areaServices.deleteArea,
    // imageUpload: 'uploadStoreImage',
    // imageRemove: 'delStoreImage'
  }

  public expandedRowKeys = []

  public mounted() {
    // this.getData()
    this.init()
  }

  public async getData() {
    const res = await this.getTableList()
    // this.tableData = res.data || []
    this.init(res.data)
  }

  public init(children: IArea[] = []) {
    this.tableData = [
      {
        ...this.currentUserArea,
        hasChild: true,
        children: children,
      },
    ]
  }

  // 更新当前数据状态
  public handleUpdateStatus(val: number, row: any) {
    const status = val ? '1' : '2'
    this.$api
      .updateStore({
        sid: row.sid,
        gid: row.gid,
        zt: status,
      })
      .then((res: Api.ResponseOptions) => {
        row.zt = status
        this.$message.success('更新成功')
      })
  }

  // @ts-ignore
  public visibleMethod({ row, type }) {
    let xTree = this.$refs.xTree
    if (type === 'body') {
      this.bodyMenus.forEach((list) => {
        list.forEach((item) => {
          if (['clearLoaded', 'reloadNodes'].includes(item.code)) {
            item.disabled = !row.hasChild || !xTree.isTreeExpandLoaded(row)
          } else if (['expand', 'contract'].includes(item.code)) {
            if (row.hasChild) {
              let isExpand = xTree.isTreeExpandByRow(row)
              item.disabled = ['expand'].includes(item.code)
                ? isExpand
                : !isExpand
            } else {
              item.disabled = true
            }
          }
        })
      })
    }
    return true
  }

  // @ts-ignore
  public contextMenuClickEvent({ menu, row, column }) {
    let xTree = this.$refs.xTree
    switch (menu.code) {
      case 'clearLoaded':
        xTree.clearTreeExpandLoaded(row)
        break
      case 'reloadNodes':
        xTree.reloadTreeExpand(row)
        break
      case 'expand':
        xTree.setTreeExpand(row, true)
        break
      case 'contract':
        xTree.setTreeExpand(row, false)
        break
    }
  }

  // 编辑前数据预处理
  public async handleTableEdit(row: IArea) {
    const params = Object.assign({}, row)
    delete params.children
    this.tableEdit(params)
  }

  // 展开下级
  // public handlerExpandChange(expanded, record) {
  //   console.log(expanded, record)
  // }

  public async loadChildrenMethod({ row }: { row: IArea }) {
    // 异步加载子节点
    const res = await areaServices.getAreaLazy({
      s_a_id: row.s_a_id || this.currentUserArea.s_a_id,
    })
    return res.data.map(item => ({...item, hasChild: true}))
  }

  // 添加下级数据
  public handleAddNext(row: IArea) {
    this.visible = true
    this.formMode = 'add'
    this.visibleTitle = '添加下一级行政区'
    this.$nextTick(() => {
      this.currentRowRef = row
      this.currentRow = Object.assign(
        {},
        { s_up_id: row.s_a_id, s_a_id: '', s_a_nam: '' }
      )
    })
  }

  // 提交
  public async handlerFromSubmit() {
    await this.handleSubmit({}, false)
    let xTree = this.$refs.xTree
    xTree.reloadTreeExpand(this.currentRowRef)
  }
}
</script>

<style scoped>
.action-button {
  margin: 0px 10px 0px 10px;
}
.form-item-class {
  margin-bottom: 0px;
}
.img-box {
  width: 100px;
  height: 100px;
  margin: 10px;
}
.item-blue {
  color: #1989fa;
}
</style>
